import { builderUri } from '@/utils/config';
import Taro from '@tarojs/taro';
import { getCurrentInstance } from 'vue';

export function useCurrent() {
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  return current;
}

export function useRouter() {
  const current = useCurrent();
  const eventChannel = current?.getOpenerEventChannel();
  function link(url, data, type = 'navigateTo') {
    if (typeof data == 'function') {
      type = data;
      data = null;
    }
    const __ = {};
    Taro[type]({
      url: url,
      events: {
        callbackEvent(data) {
          __.__callback?.call(this, data);
        }
      },
      success: function (res) {
        res.eventChannel && res.eventChannel.emit('defaultOptions', data);
      }
    });
    return {
      then(__callback) {
        __.__callback = __callback;
      }
    };
  }
  return {
    tryLink: data => {
      if (data.linkCode) {
        const url = builderUri(data.linkCode, data.linkParams);
        if (url) {
          return link(url);
        }
      }
    },
    back: (data, delta) => {
      Taro.navigateBack({ delta: delta }).then(res => {
        if (!eventChannel || !eventChannel.emit) {
          return;
        }
        eventChannel.emit('callbackEvent', data);
      });
    },
    callback(data) {
      if (!eventChannel || !eventChannel.emit) {
        return;
      }
      eventChannel.emit('callbackEvent', data);
    },
    push(url, data) {
      return link(url, data);
    },
    replace(url, data) {
      return link(url, data, 'redirectTo');
    },
    reload(url, data) {
      return link(url, data, 'reLaunch');
    },
    switch(url, data) {
      return link(url, data, 'switchTab');
    },
    getData: () => {
      return new Promise(resolve => {
        if (!eventChannel || !eventChannel.on) {
          return resolve(null);
        }
        eventChannel.on('defaultOptions', function (data) {
          resolve(data);
        });
      });
    },
    link
  };
}
